/* eslint-disable camelcase */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, Table, Popover, Icon, Empty } from 'antd';
import _ from 'lodash';
import { getOneDayList } from '@api/task';
import { LEVEL_TEXT, LEVEL_COLOR } from '@util/constants';
import WeakPasswordModal from '../components/weak-password-modal';
import './index.less';
import cn from 'classnames';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { actions as assetManageActions } from '../../asset-manage/reducer';

const prefixCls = 'weak-password';
const Search = Input.Search;

class OneDayDetectionContent extends Component {
  constructor(props) {
    super(props);
    const filterString = sessionStorage.getItem('filter_weakPasswordFilter');
    let filter = {};
    try {
      filterString && (filter = JSON.parse(filterString));
      if (filter.affected) {
        filter.affected = JSON.parse(filter.affected);
      }
      // eslint-disable-next-line
    } catch (error) {}
    this.state = {
      loading: false,
      filter,
      sort: {},
      total: 0,
      tableList: [],
      oneDayModalVisible: false,
      selectedRowKeys: [],
      record: {},
      selectedRows: []
    };
  }

  componentDidMount() {
    this.getOneDayList();
  }

  //获取1DAY漏洞插件列表
  getOneDayList = () => {
    const { filter = {}, sort = {} } = this.state;
    this.setState({ loading: true });
    getOneDayList({ ...filter, ...sort, isWeakPassword: true })
      .then(res => {
        const data = res.data.data;
        this.setState({
          loading: false,
          tableList: _.get(data, 'list', []),
          total: _.get(data, 'count', 0)
        });
      })
      .catch(() => this.setState({ loading: false }));
    sessionStorage.setItem('filter_weakPasswordFilter', JSON.stringify(filter));
  };

  onSearchChange = e => {
    let { filter } = this.state;
    filter.search = e.target.value;
    this.setState({ filter });
  };

  onTableChange = (pagination, filters, sorter) => {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0;
    const { filter } = this.state;
    const { current, pageSize } = pagination;

    const sort = {};
    if (!_.isEmpty(sorter)) {
      sort[sorter.field] = sorter.order === 'descend' ? 'down' : 'up';
    }

    filter.page = current;
    filter.pageSize = pageSize;
    filter.level = _.get(filters, 'level[0]');
    this.setState({ filter, sort }, this.getOneDayList);
  };

  wrapChangeModalVisible = (visible, record) => () => {
    this.setState({
      oneDayModalVisible: visible,
      record: record
    });
  };

  jumpToAssetByAffected = affected => {
    const { assetManageActions } = this.props;
    const affectKeys = ['component', 'service', 'os', 'title'];
    assetManageActions.resetQuery({
      search: affectKeys.map(key => `${key}="${affected}"`).join(' || ')
    });
    this.props.history.push('/asset-manage');
  };

  render() {
    const { loading, total, filter, tableList, oneDayModalVisible, record } = this.state;
    const pagination = {
      total: total,
      current: filter.page,
      pageSize: filter.pageSize,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showSizeChanger: true,
      showTotal: num => `共 ${num} 条`,
      size: 'small'
    };
    const columns = [
      {
        title: '漏洞名称',
        className: 'vul-name',
        dataIndex: 'name'
      },
      {
        title: '漏洞等级',
        dataIndex: 'level',
        width: 120,
        filters: [
          { text: '严重漏洞', value: 'fatal' },
          { text: '高危漏洞', value: 'high' },
          { text: '中危漏洞', value: 'middle' },
          { text: '低危漏洞', value: 'low' }
        ],
        filterMultiple: false,
        filteredValue: this.state.filter.level ? [this.state.filter.level] : [],
        render: level => {
          return (
            <span
              style={{
                color: LEVEL_COLOR[level],
                borderColor: LEVEL_COLOR[level],
                border: '1px solid',
                borderRadius: '20px',
                padding: '2px 10px',
                fontSize: '12px'
              }}
            >
              {LEVEL_TEXT[level]}
            </span>
          );
        }
      },
      {
        title: '真实影响资产',
        width: 140,
        dataIndex: 'real',
        sorter: true,
        render: (v, record) => {
          const real = _.get(record, 'affectedSiteCount.real', 0);
          const latestTaskId = _.get(record, 'latest_task_info.task_oid', '');
          const { history, assetManageActions } = this.props;
          return (
            <span
              onClick={() => {
                history.push('/asset-manage');
                assetManageActions.setState({
                  search: `vul="${record.name}"`,
                  loadAssetListIndex: Date.now(),
                  pagaition: {
                    page: 1,
                    pageSize: 10
                  }
                });
              }}
              style={{ whiteSpace: 'nowrap' }}
              className="real_influence"
            >
              <span className={cn({ 'be-color': latestTaskId })}>{real}&nbsp;</span>
            </span>
          );
        }
      },
      {
        title: '可能影响资产',
        width: 140,
        dataIndex: 'suspect',
        sorter: true,
        render: (v, record) => {
          const predict = _.get(record, 'affectedSiteCount.suspect', 0);
          const affected = _.get(record, 'affected', '-');
          return (
            <span
              style={{ whiteSpace: 'nowrap', cursor: 'pointer' }}
              onClick={() => this.jumpToAssetByAffected(affected || '-')}
            >
              可能影响&nbsp;{predict}&nbsp;
              <Popover
                content={
                  <div>
                    1.您暂时还未针对该1DAY任务下发过检测任务
                    <br />
                    2.由于该漏洞影响组件/标题/操作系统/服务为“{affected || '-'}”。您有&nbsp;
                    {predict}&nbsp;个资产可能会受到该漏洞的影响
                  </div>
                }
                title=""
                overlayStyle={{ width: 380 }}
              >
                <Icon type="info-circle" />
              </Popover>
            </span>
          );
        }
      },
      {
        title: '创建时间',
        width: 140,
        dataIndex: 'created',
        sorter: true
      },
      {
        title: '操作',
        dataIndex: 'operations',
        width: 140,
        render: (operations, record) => {
          return (
            <div className="operations-row">
              <span
                className="be-color"
                onClick={() => this.props.history.push(`/vul/weak-password/${record._id}`, record)}
              >
                详情
              </span>
              <span className="be-color" onClick={this.wrapChangeModalVisible(true, record)}>
                检测
              </span>
            </div>
          );
        }
      }
    ];

    return (
      <div className={`${prefixCls}`}>
        <div className={`${prefixCls}-title`}>弱口令列表</div>
        <div className={`${prefixCls}-header`}>
          <div className={cn(`${prefixCls}-header-right`, 'autoline')}>
            <div className={`${prefixCls}-header-count`}>共有“{total}”个弱口令插件</div>
            <Search
              className="autowidth"
              enterButton
              placeholder="请输入漏洞名称"
              onSearch={value => {
                filter.search = value.toString();
                filter.page = 1;
                this.setState({ filter }, this.getOneDayList);
              }}
              onChange={this.onSearchChange}
              value={filter.search}
            />
          </div>
        </div>
        <Table
          rowKey="_id"
          loading={{ spinning: loading, tip: '加载中' }}
          locale={{
            emptyText: (
              <Empty
                description={loading ? ' ' : '暂无数据'}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )
          }}
          columns={columns}
          pagination={pagination}
          dataSource={tableList}
          rowSelection={null}
          onChange={this.onTableChange}
        />
        <WeakPasswordModal
          modalVisible={oneDayModalVisible}
          closeModal={this.wrapChangeModalVisible(false)}
          data={record}
        />
      </div>
    );
  }
}

OneDayDetectionContent.propTypes = {
  history: PropTypes.object,
  name: PropTypes.string,
  modules: PropTypes.array,
  assetManageActions: PropTypes.object
};

const mapStateToProps = state => {
  return {
    modules: _.get(state, 'auth.cert.modules', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    assetManageActions: bindActionCreators(assetManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(OneDayDetectionContent);
